'use strict';

const uidObj = require('uni-id');
const uidPay = require('uni-pay');

const uniConfig = require('uni-config-center');
const uidConfig = uniConfig({
	pluginId: 'uni-id'
}).config();

const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;

module.exports = class PayController extends Controller {

	// 支付下单
	async order() {
		let response = {
			code: 1,
		};

		const start = new Date().getTime();
		const {
			code,
			pay_openid, // 付款人 openid
			pay_way,
			pay_original,
			pay_trade_type,
			money,
			moneyId,
			title,
			order_id
		} = this.ctx.data;
		let uid = '';
		let app_id
		let shop_id
		let openid
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				app_id = userRes.userInfo.app_id
				shop_id = userRes.userInfo.shop_id
				openid = userRes.userInfo.openid
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}

		if (money <= 0) {
			response.msg = '支付金额需大于0';
			return response;
		}
		// 配置项
		const config = this.service.utils.getConfig();

		const fee = money * 100;
		let recharge = await this.db.collection('wmzmall-recharge').doc(moneyId).get()
		recharge = recharge.data[0]
		let get_money = recharge.arrival
		let entitlement_id = recharge.entitlement_id
		let vip = recharge.vip
		const paytitle = `${config.appname}-${title}`;
		let payid = order_id || ('wmzmall-' + new Date().getTime() + (Math.round(Math.random() * 1000000) + '')
			.padStart(6, '0'));
		let payres = '';
		let paypreid = '';
		let payOrderInfo = {};
		switch (pay_way) {
			case '微信支付':
				let wxpayOrderInfo = {};
				switch (pay_trade_type) {
					case 'APP': // APP
					case 'MWEB': // H5 微信外部浏览器
					case 'H5WX': // H5 微信公众号（内部浏览器）
					case 'NATIVE': // 二维码
						break;
					default: // 小程序微信支付
						wxpayOrderInfo = await this.service.wechat.pay(app_id, openid, payid, fee, paytitle,
							"/notify-recharge/wxpay-app")
						wxpayOrderInfo = wxpayOrderInfo.data
						break;
				}
				// 下单支付参数
				payOrderInfo = wxpayOrderInfo;

				paypreid = wxpayOrderInfo.prepayId;
				payres = JSON.stringify(wxpayOrderInfo);
				break;
			case '支付宝':
				let alipayOrderInfo = {};
				switch (pay_trade_type) {
					case 'APP':
						break;
					default: // 小程序支付宝支付
						alipayOrderInfo = await this.service.alipay.pay(app_id, openid, payid, fee, paytitle,
							"/notify-recharge/alipay-app")
						// 下单支付参数
						payOrderInfo = {
							trade_no: alipayOrderInfo.data
						};
						break;
				}

				uniCloud.logger.info("alipayOrderInfo: ", alipayOrderInfo);

				paypreid = alipayOrderInfo.prepayId;
				payres = JSON.stringify(alipayOrderInfo);
				break;
			case '百度钱包':
				break;
			case 'QQ钱包':
				break;
			case '头条支付':
				break;
			case '余额支付':
				break;
			default:
				break;
		}

		await this.db.collection('wmzmall-member-pay').doc(payid).set({
			pay_id: payid,
			pay_money: money,
			get_money: get_money,
			pay_openid: openid,
			pay_title: title,
			pay_way: pay_way,
			pay_original: pay_original,
			pay_trade_type: pay_trade_type,
			pay_preid: paypreid,
			pay_res: payres,
			vip: vip,
			entitlement_id:entitlement_id,
			pay_state: '待付款',
			version: 1,
			is_delete: 0,
			create_uid: uid,
			create_time: new Date().getTime()
		});

		// 返回下单数据
		payOrderInfo.pay_id = payid;
		response.datas = payOrderInfo;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}

	// 支付状态查询
	async state() {
		let response = {
			code: 1,
			msg: '支付状态查询失败'
		};

		const {
			pay_id
		} = this.ctx.data;

		if (!pay_id) {
			response.msg = '交易号不存在';
			return response;
		}

		// 查询订单支付状态
		const payRes = await this.db.collection('wmzmall-member-pay').where({
			pay_id
		}).get();
		if (!payRes || payRes.data.length !== 1) {
			response.msg = '支付单不存在';
			return response;
		}

		const payObj = payRes.data[0];
		if (payObj.pay_state == '已付款') {
			response.code = 0;
			response.datas = {
				pay_state: payObj.pay_state,
				pay_id: payObj.pay_id
			};
			return response;
		}

		switch (payObj.pay_way) {
			case '微信支付':
				const uniWxpayIns = uidPay.initWeixin(uidConfig['mp-weixin']['pay']);
				const uniWxpayRes = await uniWxpayIns.orderQuery({
					outTradeNo: pay_id,
				});

				response.code = 0;
				response.datas = {
					pay_state: payObj.pay_state,
					pay_id: payObj.pay_id,
					trade_state: uniWxpayRes.tradeState
				};
				return response;
			case '支付宝':
				const uniAlipayIns = uidPay.initWeixin(uidConfig['mp-alipay']['pay']);
				const uniAlipayRes = await uniAlipayIns.orderQuery({
					outTradeNo: pay_id,
				});

				response.code = 0;
				response.datas = {
					pay_state: payObj.pay_state,
					pay_id: payObj.pay_id,
					trade_state: uniAlipayRes.tradeState
				};
				return response;
		}

		return response;
	}

	// 支付成功
	async success() {
		let response = {
			code: 1,
		};

		const start = new Date().getTime();
		const nowdate = start;
		const {
			pid
		} = this.ctx.data;

		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}

		if (!pid) {
			response.msg = `订单不存在`;
			return response;
		}

		const orderRes = await this.db.collection('wmzmall-member-pay').doc(pid).get();
		const [orderPay] = orderRes.data;
		if (!orderPay) {
			response.msg = `订单[${pid}]不存在`;
			return response;
		}

		const payLogRes = await this.db.collection('wmzmall-member-money-log').doc(pid).get();
		const [payLog] = payLogRes.data;
		if (!payLog) {
			await this.db.collection('wmzmall-member-money-log').doc(pid).set({
				user_uid: uid,
				order_id: pid,
				express_cost: 0,
				money: orderPay.pay_money,
				money_fmt: '+' + orderPay.pay_money,
				source: orderPay.pay_way,
				state: '待核实',
				type: '充值',
				remark: `通过${orderPay.pay_way}充值+${orderPay.pay_money}`,
				ip: '',
				is_delete: 0,
				create_uid: uid,
				create_time: nowdate
			});
		}

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}
}